package com.baor.service.impl;

import com.baor.dao.DeliveryRecordDao;
import com.baor.dao.EquipmentDao;
import com.baor.domain.DeliveryRecordVO;
import com.baor.domain.Equipment;
import com.baor.service.HaveSubmittedService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HaveSubmittedServiceImpl implements HaveSubmittedService {

    @Autowired
    private DeliveryRecordDao deliveryRecordDao;

    @Autowired
    private EquipmentDao equipmentDao;

    @Override
    public R haveSubmitted(Map<String, Object> params) {
        try {
            // 1. 验证参数是否包含userId
            if (params.get("userId") == null) {
                return R.er("用户ID不能为空");
            }

            Integer userId;
            try {
                userId = Integer.parseInt(params.get("userId").toString());
            } catch (NumberFormatException e) {
                return R.er("用户ID格式错误，请传入有效的数字");
            }

            // 2. 根据userId查询delivery_record表中匹配的equipment_id
            MPJLambdaWrapper<DeliveryRecordVO> recordWrapper = new MPJLambdaWrapper<>(DeliveryRecordVO.class)
                    .select(DeliveryRecordVO::getEquipmentId)
                    .eq(DeliveryRecordVO::getUserId, userId)
                    .groupBy(DeliveryRecordVO::getEquipmentId); // 去重设备ID

            List<Map<String, Object>> recordMaps = deliveryRecordDao.selectJoinMaps(recordWrapper);
            if (recordMaps.isEmpty()) {
                return R.ok(new HashMap<String, Object>() {{
                    put("totalSize", 0);
                    put("equipmentList", new ArrayList<>());
                }});
            }

            // 3. 提取设备ID列表
            List<Integer> equipmentIds = recordMaps.stream()
                    .map(map -> {
                        Object equipmentIdObj = map.get("equipment_id");
                        return equipmentIdObj != null ? Integer.parseInt(equipmentIdObj.toString()) : null;
                    })
                    .filter(id -> id != null)
                    .collect(Collectors.toList());

            if (equipmentIds.isEmpty()) {
                return R.ok(new HashMap<String, Object>() {{
                    put("totalSize", 0);
                    put("equipmentList", new ArrayList<>());
                }});
            }

            // 4. 根据设备ID列表查询设备表信息
            MPJLambdaWrapper<Equipment> equipmentWrapper = new MPJLambdaWrapper<>(Equipment.class)
                    .selectAll(Equipment.class)
                    .eq(Equipment::getIsDeleted, 0)
                    .in(Equipment::getId, equipmentIds);

            List<Equipment> equipmentList = equipmentDao.selectList(equipmentWrapper);

            // 5. 处理设备数据，计算百分比
            List<Map<String, Object>> processedEquipmentList = equipmentList.stream()
                    .map(equipment -> {
                        Map<String, Object> equipmentMap = new HashMap<>();
                        // 复制设备原有属性
                        equipmentMap.put("id", equipment.getId());
                        equipmentMap.put("code", equipment.getCode());
                        equipmentMap.put("nowWeight", equipment.getNowWeight());
                        equipmentMap.put("threshold", equipment.getThreshold());
                        equipmentMap.put("address", equipment.getAddress());
                        equipmentMap.put("is_status", equipment.getIsStatus());
//                        equipmentMap.put("isDeleted", equipment.getIsDeleted());
//                        equipmentMap.put("isUelected", equipment.getIsUelected());
                        // 可以继续添加其他需要的属性...

                        // 计算 now_weight/threshold*100%
                        Double percentage = calculatePercentage(equipment.getNowWeight(), equipment.getThreshold());
                        equipmentMap.put("percentage", percentage);

                        return equipmentMap;
                    })
                    .collect(Collectors.toList());

            // 6. 封装返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("totalSize", processedEquipmentList.size());
            result.put("equipmentList", processedEquipmentList);

            return R.ok(result);

        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败: " + e.getMessage());
        }
    }

    /**
     * 计算百分比 (nowWeight / threshold * 100%)
     * @param nowWeight 当前重量 (BigDecimal类型)
     * @param threshold 阈值 (BigDecimal类型)
     * @return 百分比值，如果threshold为0则返回0.0
     */
    private Double calculatePercentage(BigDecimal nowWeight, BigDecimal threshold) {
        if (threshold == null || threshold.compareTo(BigDecimal.ZERO) == 0) {
            return 0.0;
        }
        if (nowWeight == null) {
            return 0.0;
        }

        // 使用BigDecimal进行精确计算，保留2位小数
        BigDecimal percentage = nowWeight
                .multiply(new BigDecimal("100.0"))
                .divide(threshold, 2, BigDecimal.ROUND_HALF_UP);

        return percentage.doubleValue();
    }
}